package com.chidopi.market.aa.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.chidopi.market.aa.domain.Roles;
import com.chidopi.market.aa.service.IPermissionService;

public class CustomInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource{
	
	private static Logger logger = LoggerFactory.getLogger(CustomInvocationSecurityMetadataSource.class);
	
	@Autowired
	@Qualifier("permissionService")
	private IPermissionService permissionService;
	
	@Override
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		
		String url = ((FilterInvocation)object).getRequestUrl();
		if(url.startsWith("/")) url=url.substring(1);
		
		if(logger.isDebugEnabled()){
			logger.debug("URL: " + url);
		}
		if(!url.endsWith(".do")) return null;
		
		List<Roles> roles = null;
		Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
		try{
			roles = permissionService.getRolesByFunctionUrl(url);
		}catch(Exception e){
			logger.warn("getRolesByFnctionUrl error" + e);			
			return atts;
		}
		
		if(roles != null && roles.size() > 0){			
			for(Roles role: roles){
				ConfigAttribute ca = new SecurityConfig(role.getRolename());				
				atts.add(ca);				
			}
			if(logger.isDebugEnabled()){
				logger.debug("getRoles: " + atts);
			}
			return atts;
		}
		
		return null;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}
}
